package com.example.baselibrary.activtity;

import android.app.Activity;
import android.content.Context;

import java.util.Stack;

/**
 * Created by sunsh on 2017/12/18.
 */

public class ActivityManager {
    private static Stack<Activity> sActivityStatcks;
    private static ActivityManager instance;

    public static ActivityManager getInstance(){
        if (instance ==null){
            instance =new ActivityManager();
            return instance;
        }else {
            return instance;
        }
    }
    // add to stack

    public void addActivity(Activity activity){
        if (sActivityStatcks ==null){
            sActivityStatcks=new Stack<Activity>();
        }
        sActivityStatcks.add(activity);
    }

    public Activity currentActivity(){
        Activity activity=sActivityStatcks.lastElement();
        return activity;
    }
    public void removeActivity(){
        Activity activity=currentActivity();
        finishActivity(activity);
    }
    /**
     * 结束当前Activity
     */
    public void finishActivity(){
        Activity activity=sActivityStatcks.lastElement();
        finishActivity(activity);
    }

    public void finishActivity(Activity activity) {
       if (activity!=null){
           sActivityStatcks.remove(activity);
           activity.finish();
           activity=null;
       }
    }

    public void finishActivity(Class<?> cls){
        for (Activity activity:sActivityStatcks){
            if (activity.getClass().equals(cls)){
                finishActivity(activity);
                return;
            }
        }
    }


    /**
     * 结束全部的Activity
     */
    public void finishAllActivity(){
        int size =sActivityStatcks.size();
        for (int i = 0;i < size; i++){
            if (null != sActivityStatcks.get(i)){
                sActivityStatcks.get(i).finish();
            }
        }
        sActivityStatcks.clear();
    }

    public void AppExit(Context context){
        try{
            finishAllActivity();
            android.app.ActivityManager activityMgr= (android.app.ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            activityMgr.restartPackage(context.getPackageName());
            System.exit(0);
        }catch (Exception e){

        }
    }




}
